package com.fjnu.service.impl;

import com.fjnu.annotation.ExceptionGlobalCatch;
import com.fjnu.dao.UserDao;
import com.fjnu.domain.dto.UserConditionDto;
import com.fjnu.domain.entity.User;
import com.fjnu.service.UserService;
import com.fjnu.domain.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@ExceptionGlobalCatch
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User queryByName(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }

        UserConditionDto condition = new UserConditionDto();
        condition.setUsername(username);
        List<User> users = userDao.selectByCondition(condition);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int register(User user) {
        if (user == null || user.getName() == null || user.getName().trim().isEmpty() ||
                user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new IllegalArgumentException("用户信息不完整");
        }

        // 检查用户名是否已存在
        User existingUser = queryByName(user.getName());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 设置默认值
        if (user.getGender() == null) {
            user.setGender(1);
        }
        if (user.getScore() == null) {
            user.setScore(0L);
        }
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        if (user.getSalt() == null) {
            user.setSalt("default_salt");
        }

        return userDao.insert(user);
    }

    @Override
    public PageResult queryUsers(UserConditionDto userCondition, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        int startIndex = (pageNum - 1) * pageSize;

        List<User> userList = userDao.selectByConditionWithLimit(userCondition, startIndex, pageSize);
        List<User> allUsers = userDao.selectByCondition(userCondition);
        int total = allUsers.size();
        int totalPages = (int) Math.ceil((double) total / pageSize);

        return new PageResult(userList, total, pageNum, pageSize, totalPages);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAssignRole(String userId, List<String> roleIds) {
        if (userId == null || roleIds == null || roleIds.isEmpty()) {
            throw new RuntimeException("参数不能为空");
        }

        Integer userIdInt = Integer.parseInt(userId);
        List<Integer> roleIdInts = roleIds.stream()
                .map(Integer::parseInt)
                .toList();

        userDao.batchInsertUserRoles(userIdInt, roleIdInts);
    }

    @Override
    public int updatePassword(Integer userId, String newPassword) {
        if (userId == null || newPassword == null || newPassword.trim().isEmpty()) {
            throw new RuntimeException("用户ID和密码不能为空");
        }
        return userDao.updatePassword(userId, newPassword);
    }
}